package com.liyuhan.shopping.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.liyuhan.shopping.dto.CommentWithUserinfo;
import com.liyuhan.shopping.dto.DataResponse;
import com.liyuhan.shopping.entity.*;
import com.liyuhan.shopping.mapper.*;
import com.liyuhan.shopping.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsTypeMapper goodsTypeMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    private Map<String, String> map = new HashMap<>();

    public DataResponse getGoodsList(){
        // 得到所有商品信息
        List<Goods> goodsList = goodsMapper.selectAll();
        map.put("goodsData", JSONObject.toJSONString(goodsList));
        return new DataResponse("200", map);
    }

    public DataResponse getGoodsType(){
        // 得到所有商品类别
        List<GoodsType> goodsTypeList = goodsTypeMapper.selectAll();
        map.put("goodsType", JSONObject.toJSONString(goodsTypeList));
        return new DataResponse("200", map);
    }

    public DataResponse getGoodsInfo(JSONObject request){
        // 根据gid获取商品信息
        String gid = request.get("gid").toString();
        // 检索商品信息
        Goods goods = goodsMapper.selectById(gid);
        // 商品类别和商家信息的获取
        GoodsType gtype = goodsTypeMapper.selectById(goods.getGtype());
        Business business = businessMapper.selectById(goods.getBid());
        // 进行封装
        map.put("goodsInfo", JSONObject.toJSONString(goods));
        map.put("goodsType", JSONObject.toJSONString(gtype));
        map.put("businessInfo", JSONObject.toJSONString(business));
        return new DataResponse("200", map);
    }

    public DataResponse getGoodsComment(JSONObject request){
        String gid = request.get("gid").toString();
        List<Comment> commentList = commentMapper.selectByGID(gid);
        List<CommentWithUserinfo> commentWithUserinfos = new ArrayList<CommentWithUserinfo>();
        for(Comment comment : commentList){
            User user = userMapper.selectById(comment.getUid());
            commentWithUserinfos.add(new CommentWithUserinfo(comment.getContent(), user.getUsername(), user.getUimage()));
        }
        // 封装
        map.put("comments", JSONObject.toJSONString(commentWithUserinfos));
        return new DataResponse("200", map);
    }
}
